<template>
    <div class="directory-management">
        <div class="search-container">
            <el-input v-model="search" placeholder="请输入目录信息查询" clearable @clear="handleClearSearch"
                class="search-input" />
            <el-button type="primary" @click="openDialog('add')">新增目录</el-button>
        </div>

        <el-table :data="directories" stripe border>
            <el-table-column prop="journal_name" label="期刊名称" />
            <el-table-column prop="cn_number" label="CN刊号" />
            <el-table-column prop="issn" label="ISSN号" />
            <el-table-column prop="postal_code" label="邮发代号" />
            <el-table-column prop="publication_cycle" label="出版周期" />
            <el-table-column prop="publication_place" label="出版地" />
            <el-table-column prop="sponsor" label="主办单位" />
            <el-table-column prop="details" label="详细信息" />
            <el-table-column prop="created_at" label="创建时间" />
            <el-table-column prop="updated_at" label="更新时间" />
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button size="small" @click="openDialog('edit', row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            v-model:current-page="currentPage" @current-change="handlePageChange" class="pagination" />

        <el-dialog v-model="dialogVisible" width="30%" :title="dialogTitle">
            <el-form :model="currentDirectory" :rules="rules" ref="form" label-width="100px">
                <el-form-item label="期刊名称" prop="journal_name">
                    <el-input v-model="currentDirectory.journal_name" placeholder="请输入期刊名称" />
                </el-form-item>
                <el-form-item label="CN刊号" prop="cn_number">
                    <el-input v-model="currentDirectory.cn_number" placeholder="请输入CN刊号" />
                </el-form-item>
                <el-form-item label="ISSN号" prop="issn">
                    <el-input v-model="currentDirectory.issn" placeholder="请输入ISSN号" />
                </el-form-item>
                <el-form-item label="邮发代号" prop="postal_code">
                    <el-input v-model="currentDirectory.postal_code" placeholder="请输入邮发代号" />
                </el-form-item>
                <el-form-item label="出版周期" prop="publication_cycle">
                    <el-input v-model="currentDirectory.publication_cycle" placeholder="请输入出版周期" />
                </el-form-item>
                <el-form-item label="出版地" prop="publication_place">
                    <el-input v-model="currentDirectory.publication_place" placeholder="请输入出版地" />
                </el-form-item>
                <el-form-item label="主办单位" prop="sponsor">
                    <el-input v-model="currentDirectory.sponsor" placeholder="请输入主办单位" />
                </el-form-item>
                <el-form-item label="详细信息" prop="datails">
                    <el-input type="textarea" v-model="currentDirectory.details" placeholder="请输入详细信息" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSave">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { journalDirectoryApi } from '@/request/apiService';
import { ElMessageBox } from 'element-plus';

const directories = ref([]);
const currentDirectory = ref({ journal_name: '', cn_number: '', issn: '', postal_code: '', publication_cycle: '', publication_place: '', sponsor: '', details: '' });
const dialogVisible = ref(false);
const dialogTitle = ref(''); // 弹窗标题
const search = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const form = ref(null);

const rules = {
    journal_name: [{ required: true, message: '请输入期刊名称', trigger: 'blur' }],
    cn_number: [{ required: true, message: '请输入CN刊号', trigger: 'blur', }, {
        validator: (rule, value, callback) => {
            if (!value) {
                callback(); return;
            }
            const cnRegex = /^\d{2}-\d{4}\/[A-Za-z]{1,3}$/;
            if (!cnRegex.test(value)) {
                callback(new Error('CN刊号格式不正确'));
            } else {
                callback();
            }
        }
    }],
    issn: [{ required: false, message: '请输入ISSN刊号', trigger: 'blur' }, {
        validator: (rule, value, callback) => {
            if (!value) {
                callback(); return;
            }
            const issnRegex = /^(\d{4}-\d{4}|\d{8})$/;
            if (!issnRegex.test(value)) {
                callback(new Error('ISSN号格式不正确'));
            } else {
                callback();
            }
        }
    }],
    postal_code: [{ required: false, message: '请输入邮发代号', trigger: 'blur' }, {
        validator: (rule, value, callback) => {
            if (!value) {
                callback(); return;
            }
            const postal_codeRegex = /^\d{1,2}-\d{1,3}$/;
            if (!postal_codeRegex.test(value)) {
                callback(new Error('邮发代号号格式不正确'));
            } else {
                callback();
            }
        }
    }],
    publication_cycle: [{ required: false, message: '请输入出版周期', trigger: 'blur' }],
    publication_place: [{ required: false, message: '请选择馆藏地', trigger: 'change' }],
    sponsor: [{ required: false, message: '请输入主办单位', trigger: 'blur' }],
    details: [{ required: false, message: '请输入详细信息', trigger: 'blur' }],
};

// 获取目录列表
const fetchDirectories = async () => {
    try {
        const { data, total: totalCount } = await journalDirectoryApi.getDirectoryList({
            page: currentPage.value,
            pageSize: pageSize.value,
            search: search.value,
        });
        directories.value = data;
        total.value = totalCount;
    } catch (error) {
        console.error('获取目录列表失败', error);
    }
};

// 打开新增或编辑目录弹窗
const openDialog = (type, directory = { journal_name: '', cn_number: '', issn: '', postal_code: '', publication_cycle: '', publication_place: '', sponsor: '', details: '' }) => {
    if (type === 'add') {
        dialogTitle.value = '新增目录';
        currentDirectory.value = { journal_name: '', cn_number: '', issn: '', postal_code: '', publication_cycle: '', publication_place: '', sponsor: '', details: '' };
    } else if (type === 'edit') {
        dialogTitle.value = '编辑目录';
        currentDirectory.value = { ...directory };
    }
    dialogVisible.value = true;
};

// 保存目录（新增或更新）
const handleSave = async () => {
    if (!form.value) return;
    // 调用validate进行表单验证
    form.value.validate(async(valid) => {
        if (!valid) {
            console.log('表单验证失败');
            return; 
        }
        const { journal_name, cn_number, issn, postal_code, publication_cycle, publication_place, sponsor, details } = currentDirectory.value;
        try {
            if (currentDirectory.value.directory_id) {
                await journalDirectoryApi.updateDirectory(currentDirectory.value);
            } else {
                await journalDirectoryApi.addDirectory({ journal_name, cn_number, issn, postal_code, publication_cycle, publication_place, sponsor, details });
            }
            await fetchDirectories();
            dialogVisible.value = false;
        } catch (error) {
            console.error('保存目录失败', error);
        }
    });
};

// 删除目录
const handleDelete = (directory) => {
    ElMessageBox.confirm('此操作将永久删除该目录, 是否继续?', '警告', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                await journalDirectoryApi.deleteDirectory({ directory_id: directory.directory_id });
                await fetchDirectories();
            } catch (error) {
                console.error('删除目录失败', error);
            }
        })
        .catch(() => console.log('删除操作已取消'));
};

// 清空搜索框
const handleClearSearch = () => {
    search.value = '';
    currentPage.value = 1;
    fetchDirectories();
};

// 分页改变时触发
const handlePageChange = (page) => {
    currentPage.value = page;
    fetchDirectories();
};

// 页面加载时，获取目录数据
onMounted(fetchDirectories);

// 监听搜索变化自动获取数据
watch(search, fetchDirectories);
</script>

<style scoped>
.directory-management {
    padding: 20px;
}

.search-container {
    display: flex;
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
    margin-right: 20px;
}

.pagination {
    margin-top: 20px;
}

.dialog-footer {
    text-align: right;
}
</style>
